# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:  smart-water-iot-test
# FileName:     charge.py
# Author  :     
# Datetime:     2023/4/26 15:02
# Description：充值
# -----------------------------------------------------------------------------------
import math
import random
from time import sleep
from typing import Union, Any
from json import JSONDecodeError
from common.util.mySqlUtil.mySqlPool import select_sql
from common.util.configUtil.configUtil import ConfigUtil
from common.util.jsonUtl.jsonUtil import JsonUtil
from common.util.logUtil.logUtil import LoggerUtil
from common.util.timeUtil.timeUtil import get_now_time
from common.util.requestsUtil.requestsUtil import RequestsUtil
from core.charge.chargeApi.api import *

jsonUtil = JsonUtil()
config = ConfigUtil()
req = RequestsUtil()
logger = LoggerUtil(2)


def login():
    login_params = {"username": 17999999999, "password": "18621151d4ef64d09531b97e861b18bf", "client": 10}
    response = req.send_request("post", url=ApiCommon.LOGIN, params=login_params)
    token = response["data"]['userInfo']["token"]
    logger.info(f"登录参数：{login_params}")
    return token


def charge_api(waterNo, payMoney, token) -> dict:
    try:
        headers = {"Authorization": token}
        params = {"waterNo": waterNo, "payMoney": payMoney, "remarks": ""}
        response = req.send_request("post", url=ApiCharge.CUSTOMERCHARGE, params=params, headers=headers,
                                    parameterFormat="json")
        return response
    except JSONDecodeError as e:
        logger.error(e)


def get_blance_less_zero() -> Union[bool, Any]:
    """
    查找该项目下商户表余额小于10元的表
    """
    balanceLessThanZero = jsonUtil.read_sql("balanceLessThanZero")
    balanceLessThanZeroList = select_sql(sql=balanceLessThanZero, logType=1)
    if isinstance(balanceLessThanZeroList, list):
        if len(balanceLessThanZeroList) == 0:
            return False
        else:
            return balanceLessThanZeroList
    else:
        return balanceLessThanZeroList


def roundup(x):
    return int(math.ceil(x / 10.0)) * 10


def recharge_data(balanceLesszeroList: list = None) -> list:
    rechargeDataList = []
    if balanceLesszeroList:
        for i in balanceLesszeroList:
            if isinstance(i, list):
                # 余额
                balance = float(i[1])
                payAmount = roundup(abs(balance))
                rechargeDataList.append([i[0], payAmount, ])
            else:
                # 余额
                balance = float(balanceLesszeroList[1])
                payAmount = roundup(abs(balance))
                rechargeDataList.append([balanceLesszeroList[0], payAmount])
                break
    else:
        pass
    return rechargeDataList


def charge():
    chargeCount = 0
    chargeCountSuccess = 0
    chargeCountFail = 0
    chargeAmountSum = 0
    failInfoList = []
    try:
        token = login()
        rechargeData = recharge_data(get_blance_less_zero())
        nowTimehour = int(get_now_time(2))
        if nowTimehour >= 22 or nowTimehour <= 8:
            print(f"当前时间:{get_now_time(1)}---不在充值时间！")
            logger.debug(f"当前时间:{get_now_time(1)}---不在充值时间!")
        else:
            if isinstance(rechargeData, list) and len(rechargeData) > 0:
                for i in rechargeData:
                    response = charge_api(i[0], i[1], token)
                    if response["success"] is True:
                        print(f"正在充值: {i[0]},充值金额--->   {i[1]}  ,充值结果:--->  {response['msg']}")
                        logger.info(f"正在充值: {i[0]},充值金额--->   {i[1]}  ,充值结果:--->  {response['msg']}")
                        chargeCountSuccess += 1
                        chargeAmountSum += i[1]
                    else:
                        if response["code"] != 200:
                            chargeCountFail += 1
                            logger.error(f"表号{i[0]}: {response}")
                            failInfo = {i[0]: response['msg']}
                            failInfoList.append(failInfo)
                            print(f"正在充值: {i[0]},充值金额--->   {i[1]}   ,充值结果:--->  {response['msg']}")
                            logger.info(f"正在充值: {i[0]},充值金额--->   {i[1]}   ,充值结果:--->  {response['msg']}")
                        chargeCount += 1
            else:
                print("暂无欠费水表！")
                logger.info("暂无欠费水表！")
    except Exception as e:
        logger.error(f"charge: {e}")
        charge()
    finally:
        print(
            f"充值完成：\n  充值次数:{chargeCount}\n  充值金额:{chargeAmountSum}\n充值成功次数:{chargeCountSuccess}\n充值时间:{get_now_time(1)}\n"
            f"充值失败次数:{chargeCountFail},失败明细:{failInfoList}\n\n")
        logger.info(
            f"充值完成：\n  充值次数:{chargeCount}\n  充值金额:{chargeAmountSum}\n充值成功次数:{chargeCountSuccess}\n充值时间:{get_now_time(1)}\n"
            f"充值失败次数:{chargeCountFail},失败明细:{failInfoList}\n\n")


def charge_task() -> None:
    try:
        # schedule.every(random.randint(5, 15)).minutes.do(charge).tag("charge_Task")
        # schedule.run_all()
        # while True:
        #     schedule.run_pending()
        while True:
            charge()
            random_time = random.randint(300, 900)
            sleep(random_time)
    except Exception as e:
        logger.error(f"charge_task: {e}")


if __name__ == '__main__':
    charge()
    # print(login())
